const db = require('../db')
const moment = require('moment')
const pagify = require('utils/pagify')
const Review = require('models/Review')
const DB_NAME = 'Review'

const create = async (review) => {
  review.status = 1
  const { houseId, userId } = review

  const myreviews = await db(DB_NAME).where('houseId', houseId).where('userId', userId)
  if (myreviews.length) {
    throw {message:'请勿重复评论'}
    return
  }
  const results = await db(DB_NAME).returning('id').insert(review)
  return results[0]
}

const update = async (id, data) => {
  await Review.where({ id }).save(data, { patch: true })
  return +id
}

const auditPass = async (id) => {
  update()
  const results = await db(DB_NAME).where('id', '=', id).update({
    status: 2,
    updateTime: new Date()
  })
  return true
}

const auditReject = async (id) => {
  const results = await db(DB_NAME).where('id', '=', id).update({
    status: 3,
    updateTime: new Date()
  })
  return true
}

const toggleSelected = async (id, isSelected) => {
  const results = await db(DB_NAME).where('id', '=', id).update({
    isSelected: !!isSelected,
    updateTime: new Date()
  })
  return true
}

const remove = async (id) => {
  const results = await db(DB_NAME).where('id', '=', id).update({
    status: 0,
    updateTime: new Date()
  })
  return true
}

const getSelectedList = async (houseId) => {
  return await Review.query((qb) => {
    qb.where({
      houseId,
      isSelected: 1
    })
  }).fetchPage({
    limit: 3,
    withRelated: ['user']
  })
}

const getReviewList = async (houseId, userId, page = 1, pageSize = 10) => {
  const q = Review.query((qb) => {
    qb.where(function () {
      this.where('houseId', houseId).andWhere('status', '=', 2)
    })
    qb.orWhere(function () {
      this.where('houseId', houseId).andWhere('userId', userId)
    })
  })
  return pagify.bookshelf(q, page, pageSize, ['user'])
}

const getAll = async (params, page = 1, pageSize = 10) => {
  const q = Review.query((qb) => {
    if (params.status) {
      qb.where('status', params.status)
    }
    qb.whereNot('status', 0)
  })
  return await pagify.bookshelf(q, page, pageSize, ['user', 'house'])
}

const getReview = async (id) => {
  const review = await Review.query((qb) => {
    qb.where('id', id)
    qb.whereNot('status', 0)
  }).fetch({withRelated: ['user']})
  return review.toJSON()
}

module.exports = {
  create,   // 创建
  update,
  toggleSelected,
  auditPass, // 审核通过
  auditReject, // 审核未通过
  remove, // 删除
  getAll,
  getReviewList, // 获取对应空间评论列表
  getSelectedList, // 获取精选列表
  getReview // 获取单条
}